import cv2
import numpy as np
import os
import time
from PIL import Image
# opencv不规则裁剪


#需要处理的文件名
#IMAGE_NAME="3.jpg"
IMAGE_DIR="img/"
STORAGE_DIR="yjjy_tempt/"


#存储的图片格式
IMAGE_FORMAT=".png"



#转换存储的图片为png格式，并重命名
def trans_to_png(image_directory):
    i=1
    for file in os.listdir(IMAGE_DIR):
        img = cv2.imread(file)
        img_name=str(i)+IMAGE_FORMAT
        storage_path=os.path.join(IMAGE_DIR,img_name)
        i+=1
        cv2.imwrite(storage_path, img)


def ROI_byMouse(img, lsPointsChoose):
    mask = np.zeros(img.shape, np.uint8)
    pts = np.array(lsPointsChoose, np.int32)  # pts是多边形的顶点列表（顶点集）
    col0 = pts[:, 0]
    col1 = pts[:, 1]
    x1 = np.min(col0)
    y1 = np.min(col1)
    x2 = np.max(col0)
    y2 = np.max(col1)
    pts = pts.reshape((-1, 1, 2))
    # 这里 reshape 的第一个参数为-1, 表明这一维的长度是根据后面的维度的计算出来的。
    # OpenCV中需要先将多边形的顶点坐标变成顶点数×1×2维的矩阵，再来绘制
    # --------------画多边形---------------------
    mask = cv2.polylines(mask, [pts], True, (255, 255, 255))
    ##-------------填充多边形---------------------
    mask2 = cv2.fillPoly(mask, [pts], (255, 255, 255))

    ROI = cv2.bitwise_and(mask2, img)

    return ROI[y1:y2, x1:x2]


def crop_image(points,image_path,image_name,region_num,time):
    #os.mkdir(os.path.join(STORAGE_DIR,time))
    STORAGE_PATH = os.path.join(os.path.join(STORAGE_DIR,time), str(region_num)+"_"+image_name)
    #print(STORAGE_PATH)
    #print(STORAGE_PATH)
    #for image_path in image_path_list:
    img_ = resize_image(image_path)
    #img_ = cv2.imread(image_path)
    #print("img_:",img_)
    #print("point:",points)
    img = ROI_byMouse(img_, points)

    #print("img_roi:",img)

    cv2.imwrite(STORAGE_PATH, img)

    #print("write finished>>>>")
    #return img

def get_points(points_dic):
    w, h = [1920, 1080]
    #print(w, h)

    points_list_str_X = points_dic["pointsX"].split("|")
    points_list_X = []
    #print(points_list_str_X)
    for str in points_list_str_X:
        sub_points_X = str.split(",")
        # print("sub_points:",sub_points_x)
        points_list_X.append(sub_points_X)

    points_list_str_Y = points_dic["pointsY"].split("|")
    points_list_Y = []
    # print(points_list_str_X)
    for str in points_list_str_Y:
        sub_points_Y = str.split(",")
        # print("sub_points:",sub_points_x)
        points_list_Y.append(sub_points_Y)

    region_i = 1
    point_dic = {}
    point_list = []
    for i in range(points_list_Y.__len__()):
        single_region = []
        # print(points_list_Y[i])
        for j in range(points_list_Y[i].__len__()):
            # print(points_list_Y[i][j],points_list_X[i][j])
            x = int(int(points_list_X[i][j]) * w / 1000)
            y = int(int(points_list_Y[i][j]) * h / 1000)

            single_region.append([x, y])
        point_list.append(single_region)

    return point_list
    #print(point_list)

def resize_image(image_path):
    try:
        img=Image.open(image_path)
    except:
        img = Image.open("error.jpg")

    img = img.resize((1920, 1080))

    img.save("yjjy_tempt.jpg")

    image = cv2.imread("yjjy_tempt.jpg")

    os.remove("yjjy_tempt.jpg")
        # 放大图像
    #image.save(image_path)
    return image


def get_region_num(points):
    region_num=0
    for sub_points in points:
        if sub_points.__len__()>=3:
            region_num+=1
    #print(region_num)
    return region_num


def points_filter(points):
    points_filter = []
    for sub_points in points:
        if sub_points.__len__() >= 3:
            points_filter.append(sub_points)
    return  points_filter
    # points_filter
if __name__ == '__main__':

    box_dic={'modelId': 106, 'parentPath': '/home/leslie/ftpd/192.168.168.20',
     'nameList': ['192.168.168.20_01_20200611153004184_TIMING.jpg', '192.168.168.20_01_20200611153604718_TIMING.jpg',
                  '192.168.168.20_01_20200611153904315_TIMING.jpg', '192.168.168.20_01_20200611154204337_TIMING.jpg',
                  '192.168.168.20_01_20200611154503896_TIMING.jpg', '192.168.168.20_01_20200611154803910_TIMING.jpg',
                  '192.168.168.20_01_20200611155011816_TIMING.jpg', '192.168.168.20_01_20200611155104390_TIMING.jpg',
                  '192.168.168.20_01_20200611155704081_TIMING.jpg'],
     'pointsY': '0|489,526,552,515|526,548,580,552|552,585,619,580|589,563,597,619|564,473,492,585|473,387,403,493',
     'pointsX': '0|996,879,880,993|877,774,778,879|773,627,627,774|624,560,560,623|560,518,513,556|517,477,471,512'}

    points = get_points(box_dic)

    region_num=get_region_num(points)

    points_filter=[]
    for sub_points in points:
        if sub_points.__len__()>=3:
            points_filter.append(sub_points)
    print(points_filter)

